<?php
namespace wechat;
use SimpleXMLElement;

class Wxpay extends Base
{

    /**
     * 微信支付_统一下单接口  获取PrepayId 生成预支付交易单 不需要证书     2017-10-15
     */
    public function getprepayid($parameter)
    {
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        $data = array(
            'appid' => $parameter['appid'],
            'mch_id' => $parameter['mch_id'],
            'nonce_str' => createnoncestr(32),
            'body' => $parameter['body'],
            'out_trade_no' => $parameter['out_trade_no'],
            'total_fee' => $parameter['total_fee'] * 100,
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => $parameter['notify_url'],
            'trade_type' => 'JSAPI',
            'openid' => $parameter['openid'],
        );
        $data['sign'] = $this->getsign($data, $parameter);

        $xml = new SimpleXMLElement('<xml></xml>');
        data2xml($xml, $data);
        $data_xml = $xml->asXML();

        //设置curl超时时间
        $curl_timeout = 30;
        $response = $this->postxmlcurl($data_xml, $url, $curl_timeout);
        $result = xmltoarray($response);
        apilog(2, 'wechat', 'getprepayid', $url, $data, $result);

        isset($result["prepay_id"]) || $result["prepay_id"] = '';
        $prepay_id = $result["prepay_id"];
        return $prepay_id;
    }

    /**
     * API_统一下单接口 以post方式提交xml到对应的接口url    2017-10-15
     */
    public function postxmlcurl($xml, $url, $second = 30)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置超时
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');//这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, TRUE);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * 设置jsapi的参数 并返回     2017-10-15
     */
    public function getparameters($prepay_id, $dealarr)
    {
        $data = array(
            'appId' => $dealarr['appid'],
            'timeStamp' => (string)time(),
            'nonceStr' => createnoncestr(32),
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'MD5',
        );
        $data['paySign'] = $this->getsign($data, $dealarr);

        $parameters = json_encode($data);
        return $parameters;
    }

    /**
     * 检查本地签名    2017-10-15
     */
    public function checksign($data, $dealarr)
    {
        $tmpData = $data;
        unset($tmpData['sign']);
        $sign = $this->getsign($tmpData, $dealarr);//本地签名
        if ($data['sign'] == $sign) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 申请退款    2017-10-15
     */
    public function refund($param)
    {
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

        $data = array(
            'appid' => $param['appid'],
            'mch_id' => $param['mch_id'],
            'nonce_str' => createnoncestr(32),
            'out_trade_no' => $param['ordenumber'],
            'out_refund_no' => '@' . $param['ordenumber'],
            'total_fee' => $param['total_fee'] * 100,
            'refund_fee' => $param['refund_fee'] * 100
        );
        $data['sign'] = $this->getsign($data, $param);

        $xml = new SimpleXMLElement('<xml></xml>');
        data2xml($xml, $data);
        $data_xml = $xml->asXML();

        $result = $this->curl_post_ssl($url, $data_xml, $second = 30, $aHeader = array(), $param);
        $result = xmltoarray($result);

        apilog($param['uid'], 'wechat', 'refund', $url, serializeMysql($data), serializeMysql($result));
        return $result;
    }

    /**
     * 申请退款POST请求    2017-10-15
     */
    public function curl_post_ssl($url, $vars, $second = 30, $aHeader = array(), $parameter)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//超时时间
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');//这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . $parameter['path1']);
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . $parameter['path2']);

        //第二种方式，两个文件合成一个.pem文件
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        $data = curl_exec($ch);

        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    /**
     * 微信企业付款接口    2017-10-15
     */
    public function pay($parameter)
    {
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

        $data = array(
            'mch_appid' => $parameter['mch_appid'],    //公众账号ID
            'mchid' => $parameter['mchid'],            //商户号
            'nonce_str' => createnoncestr(32),                //随机字符串，不长于32位
            'partner_trade_no' => $parameter['ordernumber'],            //商户订单号
            'openid' => $parameter['openid'],                    //用户OPENID
            'check_name' => 'NO_CHECK',                //校验用户姓名选项，NO_CHECK：不校验真实姓名， FORCE_CHECK：强校验真实姓名OPTION_CHECK：针对已实名认证的用户才校验真实姓名
            'amount' => $parameter['money'] * 100,            //企业付款金额，单位为分
            'desc' => $parameter['desc'],            //企业付款操作说明信息
            'spbill_create_ip' => get_client_ip(),            //接口的机器Ip地址
        );
        $data['sign'] = $this->getsign($data, $parameter);//生成签名

        $xml = new SimpleXMLElement('<xml></xml>');
        data2xml($xml, $data);
        $data_xml = $xml->asXML();

        $result = $this->curl_post_ssl($url, $data_xml, $second = 30, $aHeader = array(), $parameter);
        $result = xmltoarray($result);
        apilog('', 'wechat', 'companypay', $url, serializeMysql($data), serializeMysql($result));
        return $result;
    }

    /**
     * 普通现金红包   2017-10-15
     */
    public function redbagpay($parameter)
    {
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

        $data = array(
            'nonce_str' => createnoncestr(32),                //随机字符串，不长于32位
            'mch_billno' => $parameter['mch_billno'],            //商户订单号
            'mch_id' => $parameter['mchid'],            //商户号
            'wxappid' => $parameter['mch_appid'],    //公众账号ID
            'send_name' => $parameter['send_name'],    //商户名称
            're_openid' => $parameter['openid'],                    //用户OPENID
            'total_amount' => $parameter['money'] * 100,   //付款金额，单位为分
            'total_num' => 1,   //红包发放总人数
            'wishing' => $parameter['wishing'],   //红包祝福语
            'client_ip' => get_client_ip(),            //接口的机器Ip地址
            'act_name' => $parameter['act_name'],                //活动名称
            'remark' => $parameter['remark'],    //备注
        );
        $data['sign'] = $this->getsign($data, $parameter);//生成签名
        $xml = new SimpleXMLElement('<xml></xml>');
        data2xml($xml, $data);
        $data_xml = $xml->asXML();

        $result = $this->curl_post_ssl($url, $data_xml, $second = 30, $aHeader = array(), $parameter);
        $result = xmltoarray($result);
        apilog('', 'wechat', 'redbagpay', $url, serializeMysql($data), serializeMysql($result));
        return $result;
    }

    /**
     * 获取签名    2017-10-15
     */
    public function getsign($data, $param)
    {
        foreach ($data as $k => $v) {
            if ($v) {
                $Parameters[$k] = $v;
            }
        }
        ksort($Parameters);
        $String = '';
        foreach ($Parameters as $k => $v) {
            $String .= $k . "=" . $v . "&";
        }
        $String = $String . "key=" . $param['partnerkey'];
        $String = md5($String);
        $result = strtoupper($String);

        return $result;
    }


}
